package models

import "github.com/astaxie/beego/orm"

type ContentQueryParam struct {
	BaseQueryParam
}

type Content struct {
	Id         int
	Title      string `orm:"column(title)"`
	Image      string `orm:"column(image)"`
	Content    string `orm:"column(content)"`
	Type       int    `orm:"column(type)"`
	Status     int    `orm:"column(status)"`
	ListOrder  int    `orm:"column(list_order)"`
	CategoryId int    `orm:"column(category_id)"`
	CreateAt   int64  `orm:"column(create_at)"`
	UpdateAt   int64  `orm:"column(update_at)"`
	Url        string `orm:"column(url)"`
}

func init() {
	orm.RegisterModel(new(Content))
}

func ContentTBName() string {
	return TableName("content")
}

func (u *Content) TableName() string {
	return ContentTBName()
}

func ContentPageList(params *ContentQueryParam) ([]*Content, int64) {
	query := orm.NewOrm().QueryTable(ContentTBName())
	data := make([]*Content, 0)

	sort := "Id"
	switch params.Sort {
	case "Id":
		sort = "Id"
	}

	if params.Order == "desc" {
		sort = "-" + sort
	}

	total, _ := query.Count()
	query.OrderBy(sort).Limit(params.Limit, params.Offset).All(&data)
	return data, total
}

func ContentOne(id int) (*Content, error) {
	o := orm.NewOrm()
	m := Content{Id: id}
	err := o.Read(&m)
	if err != nil {
		return nil, err
	}
	return &m, nil
}
